var t_on = {
    'apiChart': 1,
    'subsChart': 1,
    'serviceTimeChart': 1,
    'tempLoadingSpace': 1
};
var currentLocation;

var chartColorScheme1 = ["#3da0ea", "#bacf0b", "#e7912a", "#4ec9ce", "#f377ab", "#ec7337", "#bacf0b", "#f377ab", "#3da0ea", "#e7912a", "#bacf0b"];
//fault colors || shades of red
var chartColorScheme2 = ["#ED2939", "#E0115F", "#E62020", "#F2003C", "#ED1C24", "#CE2029", "#B31B1B", "#990000", "#800000", "#B22222", "#DA2C43"];
//fault colors || shades of blue
var chartColorScheme3 = ["#0099CC", "#436EEE", "#82CFFD", "#33A1C9", "#8DB6CD", "#60AFFE", "#7AA9DD", "#104E8B", "#7EB6FF", "#4981CE", "#2E37FE"];
currentLocation = window.location.pathname;
var statsEnabled = isDataPublishingEnabled();

require(["dojo/dom", "dojo/domReady!"], function (dom) {
    currentLocation = window.location.pathname;
    //Initiating the fake progress bar
    jagg.fillProgress('apiChart');
    jagg.fillProgress('subsChart');
    jagg.fillProgress('serviceTimeChart');
    jagg.fillProgress('tempLoadingSpace');

    jagg.post("/site/blocks/stats/api-response-times/ajax/stats.jag", { action: "getFirstAccessTime", currentLocation: currentLocation  },
        function (json) {

            if (!json.error) {

                if (json.usage && json.usage.length > 0) {
                    var d = new Date();
                    var firstAccessDay = new Date(json.usage[0].year, json.usage[0].month - 1, json.usage[0].day);
                    var currentDay = new Date(d.getFullYear(), d.getMonth(), d.getDate(),d.getHours(),d.getMinutes());//                    if (firstAccessDay.valueOf() == currentDay.valueOf()) {

                    //day picker
                    $('#today-btn').on('click',function(){
                        getDateTime(currentDay,currentDay-86400000);
                    });

                    //hour picker
                    $('#hour-btn').on('click',function(){
                        getDateTime(currentDay,currentDay-3600000);
                    })

                    //week picker
                    $('#week-btn').on('click',function(){
                        getDateTime(currentDay,currentDay-604800000);
                    })

                    //month picker
                    $('#month-btn').on('click',function(){
                        getDateTime(currentDay,currentDay-(604800000*4));
                    });

                    //date picker
                    $('#date-range').dateRangePicker(
                        {
                            startOfWeek: 'monday',
                            separator : ' <b>to</b> ',
                            format: 'YYYY-MM-DD HH:mm',
                            autoClose: false,
                            time: {
                                enabled: true
                            },
                            shortcuts:'hide',
                            endDate:currentDay
                        })
                        .bind('datepicker-apply',function(event,obj)
                        {
                             btnActiveToggle(this);
                             var from = convertDate(obj.date1);
                             var to = convertDate(obj.date2);
                             var fromStr = from.split(" ");
                             var toStr = to.split(" ");
                             var dateStr = fromStr[0] + " <i>" + fromStr[1] + "</i> <b>to</b> " + toStr[0] + " <i>" + toStr[1] + "</i>";
                             $("#date-range").html(dateStr);
                             drawProviderAPIServiceTime(from,to);
                        });

                    //setting default date
                    var to = new Date();
                    var from = new Date(to.getTime() - 1000 * 60 * 60 * 24 * 30);

                    getDateTime(to,from);

                    $('#date-range').click(function (event) {
                    event.stopPropagation();
                    });

                    $('body').on('click', '.btn-group button', function (e) {
                        $(this).addClass('active');
                        $(this).siblings().removeClass('active');
                    });

                    var width = $("#rangeSliderWrapper").width();
                    //$("#rangeSliderWrapper").affix();
                    $("#rangeSliderWrapper").width(width);

                }

                else if (json.usage && json.usage.length == 0 && statsEnabled) {
                    $('#middle').html("");
                    $('#middle').append($('<div class="errorWrapper"><img src="../themes/default/templates/stats/images/statsEnabledThumb.png" alt="Stats Enabled"></div>'));
                }

                else {
                    $('#middle').html("");
                    $('#middle').append($('<div class="errorWrapper"><span class="label top-level-warning"><i class="icon-warning-sign icon-white"></i>'
                        + i18n.t('errorMsgs.checkBAMConnectivity') + '</span><br/><img src="../themes/default/templates/stats/api-response-times/images/statsThumb.png" alt="Smiley face"></div>'));
                }


            }
            else {
                if (json.message == "AuthenticateError") {
                    jagg.showLogin();
                } else {
                    jagg.message({content: json.message, type: "error"});
                }
            }
            t_on['apiChart'] = 0;
        }, "json");

});

var drawProviderAPIServiceTime = function (from, to) {
    var fromDate = from;
    var toDate = to;
    jagg.post("/site/blocks/stats/api-response-times/ajax/stats.jag", { action: "getProviderAPIServiceTime", currentLocation: currentLocation, fromDate: fromDate, toDate: toDate },
        function (json) {
            if (!json.error) {

                    var length = json.usage.length, s1 = [];
                    var data = [];

                    if (length > 0) {
                    $('#tempLoadingSpace').empty();
                    $('#tableContainer').empty();
                    $('#chartContainer').empty();


                    var $dataTable = $('<table class="display defaultTable" width="100%" cellspacing="0" id="apiSelectTable"></table>');
                        $dataTable.append($('<thead class="tableHead"><tr>' +
                            '<th width="10%"></th>' +
                            '<th>API</th>' +
                            '<th width="30%" style="text-transform:none;text-align:right">RESPONSE TIME(ms)</th>'+
                            '</tr></thead>'));


                    var chartData=[];
                    var state_array = [];
                    var defaultFilterValues=[];
                    var filterValues=[];

                        for (var i = 0; i < length; i++) {
                            chartData.push({"label":json.usage[i].apiName,"value":parseFloat(json.usage[i].serviceTime)})
                        }

                        chartData.sort(function(obj1, obj2) {
                            return obj2.value - obj1.value;
                        });

                        //default display of 15 checked entries on table
                        for (var i = 0; i < chartData.length; i++) {
                            if(i<15){
                                $dataTable.append($('<tr><td >'
                                    + '<input name="item_checkbox"  checked   id=' + i + '  type="checkbox"  data-item=' + chartData[i].label
                                    + ' class="inputCheckbox" />'
                                    + '</td><td style="text-align:left;"><label for=' + i + '>' + chartData[i].label + '</label></td>'
                                    + '<td style="text-align:right;"><label for=' + i + '>' + chartData[i].value + '</label></td></tr>'));
                                filterValues.push({"label":chartData[i].label,"value":chartData[i].value});
                                state_array.push(true);
                                defaultFilterValues.push({"label":chartData[i].label,"value":chartData[i].value});
                            } else {

                                $dataTable.append($('<tr><td >'
                                     + '<input name="item_checkbox" id=' + i + '  type="checkbox"  data-item=' + chartData[i].label
                                     + ' class="inputCheckbox" />'
                                     + '</td><td style="text-align:left;"><label for=' + i + '>' + chartData[i].label + '</label></td>'
                                     + '<td style="text-align:right;"><label for=' + i + '>' + chartData[i].value + '</label></td></tr>'));
                                filterValues.push({"label":chartData[i].label,"value":chartData[i].value});
                                state_array.push(false);
                            }
                        }

                        var data_chart = [{
                              'values': defaultFilterValues,
                              'key': 'Time',
                        }];

                        var chart;
                        nv.addGraph(function() {
                            chart = nv.models.multiBarHorizontalChart()
                                .x(function(d) { return d.label })
                                .y(function(d) { return d.value })
                                .margin({top: 0, right: 25, left: 25,bottom:50})
                                .barColor(d3.scale.category20().range())
                                .tooltips(false)
                                .showControls(true);

                        chart.yAxis
                            .axisLabel('Response Time(ms)');

                        chart.yAxis.tickFormat(d3.format('d'));
                        chart.valueFormat(d3.format('d'));

                            d3.select('#serviceTimeChart svg')
                                .datum(data_chart)
                                .call(chart);

                            d3.selectAll(".nv-bar")
                                .append("text")
                                .attr("y", $('rect').attr('height')/2)
                                .attr("x", function(d) {
                                  return d3.select(this.previousSibling).attr('width')+5 ;
                                })
                                .text(function(d) {
                                  return d.label +" : "+ d.value;
                                })

                            return chart;
                        });

                        if(length<2||length==2){
                            $('#chartContainer').append($('<div id="serviceTimeChart" class="with-3d-shadow with-transitions"><svg style="height:300px;"></svg></div>'));
                        }else{
                            $('#chartContainer').append($('<div id="serviceTimeChart" class="with-3d-shadow with-transitions"><svg style="height:500px;"></svg></div>'));
                        }
                        $('#chartContainer').show();
                        $('#serviceTimeChart svg').show();
                        $('#tableContainer').append($dataTable);
                        $('#tableContainer').show();
                        $('#apiSelectTable').DataTable({
                             retrieve: true,
                             "order": [
                                 [ 2, "desc" ]
                             ],
                            "fnDrawCallback": function(){
                                if(this.fnSettings().fnRecordsDisplay()<=$("#apiSelectTable_length option:selected" ).val()
                                || $("#apiSelectTable_length option:selected" ).val()==-1)
                                    $('#apiSelectTable_paginate').hide();
                                else
                                    $('#apiSelectTable_paginate').show();
                            },
                             "aoColumns": [
                                 { "bSortable": false },
                                 null,
                                 null
                             ],
                         });
                         $('select').css('width','60px');

                        var count=15;
                        //on checkbox check and uncheck event
                        $('#apiSelectTable').on('change', 'input.inputCheckbox', function () {

                            $('#chartContainer').empty();
                            var id = $(this).attr('id');
                            var check = $(this).is(':checked');
                            var tickValue = $(this).attr('data-item');
                            var draw_chart = [];

                            if (check) {
                            $('#displayMsg').html('');
                                count++;
                                //limiting to show 15 entries at a time
                                if(count>15){
                                    $('#displayMsg').html('<h5 style="color:#555">Please Note that the graph will be showing only 15 entries</h5>');
                                    state_array[id] = false;
                                    $(this).prop("checked", "");
                                    count--;
                                }else{
                                state_array[id] = true;
                                }
                            } else {
                                $('#displayMsg').html('');
                                state_array[id] = false;
                                count--;
                            }

                            for(var i=0;i<filterValues.length;i++){
                                if (state_array[i]) {
                                    draw_chart.push({"label":filterValues[i].label,"value":filterValues[i].value});
                                }
                            }

                            //data for checked values
                            var data_chart = [{
                                  'values': draw_chart,
                                  'key': 'Time',
                            }];

                                var chart;
                                nv.addGraph(function() {
                                    chart = nv.models.multiBarHorizontalChart()
                                        .x(function(d) { return d.label })
                                        .y(function(d) { return d.value })
                                        .margin({top: 0, right: 25, left: 25,bottom:50})
                                        .barColor(d3.scale.category20().range())
                                        .tooltips(false)
                                        .showControls(false);

                                chart.yAxis.axisLabel('Response Time(ms)');
                                chart.yAxis.tickFormat(d3.format('d'));
                                chart.valueFormat(d3.format('d'));

                                d3.select('#serviceTimeChart svg')
                                    .datum(data_chart)
                                    .call(chart);

                                d3.selectAll(".nv-bar")
                                    .append("text")
                                    .attr("y", $('rect').attr('height') /2)
                                    .attr("x", function(d) {
                                      return d3.select(this.previousSibling).attr('width');
                                    })
                                    .text(function(d) {
                                      return d.label + " : "+ d.value;
                                    })

                                return chart;
                            });

                            if(draw_chart.length<2||draw_chart.length==2){
                                $('#chartContainer').append($('<div id="serviceTimeChart" class="with-3d-shadow with-transitions"><svg style="height:300px;"></svg></div>'));
                            }else{
                                $('#chartContainer').append($('<div id="serviceTimeChart" class="with-3d-shadow with-transitions"><svg style="height:500px;"></svg></div>'));
                            }
                            $('#serviceTimeChart svg').show();
                        });
                    }else if(length == 0) {
                        $('#chartContainer').hide();
                        $('#tableContainer').hide();
                        $('#tempLoadingSpace').html('');
                        $('#tempLoadingSpace').append($('<h3 class="no-data-heading center-wrapper">No Data Available</h3>'));
                    }
            } else {
                if (json.message == "AuthenticateError") {
                    jagg.showLogin();
                } else {
                    jagg.message({content: json.message, type: "error"});
                }
            }
            t_on['serviceTimeChart'] = 0;
        }, "json");
}

function isDataPublishingEnabled(){
    jagg.post("/site/blocks/stats/api-response-times/ajax/stats.jag", { action: "isDataPublishingEnabled"},
        function (json) {
            if (!json.error) {
                statsEnabled = json.usage;
                return statsEnabled;
            } else {
                if (json.message == "AuthenticateError") {
                    jagg.showLogin();
                } else {
                    jagg.message({content: json.message, type: "error"});
                }
            }
        }, "json");        
}

var convertTimeString = function(date){
    var d = new Date(date);
    var formattedDate = d.getFullYear() + "-" + formatTimeChunk((d.getMonth()+1)) + "-" + formatTimeChunk(d.getDate())+" "+formatTimeChunk(d.getHours())+":"+formatTimeChunk(d.getMinutes());
    return formattedDate;
};

var convertTimeStringPlusDay = function (date) {
    var d = new Date(date);
    var formattedDate = d.getFullYear() + "-" + formatTimeChunk((d.getMonth() + 1)) + "-" + formatTimeChunk(d.getDate() + 1);
    return formattedDate;
};

var formatTimeChunk = function (t) {
    if (t < 10) {
        t = "0" + t;
    }
    return t;
};

function convertDate(date) {
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour=date.getHours();
    var minute=date.getMinutes();
    return date.getFullYear() + '-' + (('' + month).length < 2 ? '0' : '')
        + month + '-' + (('' + day).length < 2 ? '0' : '') + day +" "+ (('' + hour).length < 2 ? '0' : '')
        + hour +":"+(('' + minute).length < 2 ? '0' : '')+ minute;
}

function btnActiveToggle(button){
    $(button).siblings().removeClass('active');
    $(button).addClass('active');
}

function getDateTime(currentDay,fromDay){
    var to = convertTimeString(currentDay);
    var from = convertTimeString(fromDay);
    var toDate = to.split(" ");
    var fromDate = from.split(" ");
    var dateStr= fromDate[0]+" <i>"+fromDate[1]+"</i> <b>to</b> "+toDate[0]+" <i>"+toDate[1]+"</i>";
    $("#date-range").html(dateStr);
    $('#date-range').data('dateRangePicker').setDateRange(from,to);
    drawProviderAPIServiceTime(from,to);
}

